package org.charles.zhifou.common.config;

import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.annotation.PostConstruct;
import jakarta.annotation.Resource;
import org.charles.zhifou.common.enums.StringToBaseEnumConverterFactory;
import org.springframework.context.annotation.Configuration;
import org.springframework.format.FormatterRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * <h1>Web 相关配置</h1>
 *
 * @author charles
 * @version 1.0
 */
@Configuration
public class WebMvcConfiguration implements WebMvcConfigurer {

    @Resource
    private ObjectMapper objectMapper;

    /* todo: 不知道为啥不生效 */
    @Resource
    private StringToBaseEnumConverterFactory stringToBaseEnumConverterFactory;

    /**
     * 注册自定义枚举类转换工厂 (仅用于 parmas 参数)
     * @param registry
     */
    @Override
    public void addFormatters(FormatterRegistry registry) {
        // 将自定义 ConverterFactory 添加到 SpringMVC 中
        registry.addConverterFactory(stringToBaseEnumConverterFactory);
    }

    /**
     * SpringBoot 参数校验相关配置
     */
    @PostConstruct
    public void enumObjectMapper() {
        // 参考博客: https://blog.csdn.net/qq_20919883/article/details/115787530

        // 解决 enum 不匹配问题 默认值为 false
        objectMapper.configure(DeserializationFeature.READ_UNKNOWN_ENUM_VALUES_AS_NULL, true);
        // 将空字符串映射为 null, 搭配全局异常处理使用
        objectMapper.enable(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT);
    }

}
